/**
 * 颜色渐变阶梯过度
 * @param startColor #ff0000 开始色
 * @param endColor #00ff00 结束色
 * @param step 步数
 * @returns {*[]} 返回rgb数组[[r,g,b]...]
 */
export function gradientColor(startColor, endColor, step = 2) {
  let [startR, startG, startB] = hexToRgb(startColor);
  let [endR, endG, endB] = hexToRgb(endColor);
  // rgb差值
  let sR = (endR - startR) / step;
  let sG = (endG - startG) / step;
  let sB = (endB - startB) / step;
  let colorArr = [];
  for (let i = 0; i < step; i++) {
    let r = parseInt(startR + sR * i);
    let g = parseInt(startG + sG * i);
    let b = parseInt(startB + sB * i);
    // let hex = rgbToHex(`rgb(${r},${g},${b})`);
    colorArr.push([r, g, b]);
  }
  return colorArr;
  // console.log(colorArr);
}

/**
 * hex色值转换为rgb
 * @param hexColor 原始hex色值
 * @returns {*[]} 返回rgb数组
 */
export function hexToRgb(hexColor) {
  // 先去掉#
  hexColor = hexColor.replaceAll("#", "");
  let reg = /^([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
  hexColor = hexColor.toLowerCase();
  if (hexColor && reg.test(hexColor)) {
    // 如果是三位简写转成6位
    let color6Str = "";
    if (hexColor.length === 3) {
      for (let i = 0; i < 3; i++) {
        color6Str += hexColor.slice(i, i + 1).concat(hexColor.slice(i, i + 1));
      }
      hexColor = color6Str;
    }
    // 转成数组
    let color6Arr = [];
    for (let i = 0; i < 6; i += 2) {
      color6Arr.push(parseInt(`0x${hexColor.slice(i, i + 2)}`));
    }
    return color6Arr;
  }
  return null;
}

/**
 * rgb色值转hex
 * @param rgbColor rgb(0,0,0)/RGB(0,0,0)
 * @returns {string} #ff0000
 */
export function rgbToHex(rgbColor) {
  // 去除原始字符串里的rgb()并转成数组
  // let rgbColorArr = rgbColor.substring(4, rgbColor.length - 1).split(",");
  let rgbColorArr = rgbColor.replace(/\(|\)|rgb|RGB/g, "").split(",");
  if (rgbColorArr.length === 3) {
    let hexColorStr = "";
    rgbColorArr.forEach((item) => {
      let hex = Number(item).toString(16);
      hex = hex < 10 ? `0${hex}` : hex;
      hexColorStr += hex;
    });
    return "#" + hexColorStr;
  }
  return "";
}
